package com.heima.wemedia.scan.service.iml;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.heima.aliyun.green.AliyunGreenTemplate;
import com.heima.common.contants.MessageConstants;
import com.heima.wemedia.scan.service.NewsScanService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsScanServiceImpl implements NewsScanService {

    @Resource
    private AliyunGreenTemplate aliyunGreenTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /***
     * 文章审核
     * @param newsId
     * @param text
     * @param images
     */
    @Override
    public void scan(Long newsId, String text, List<String> images) throws Exception {
        //初始审核状态
        String suggestion="pass";
        String reason="审核通过";

        //1、文本审核
        Map<String, String> resultMap = aliyunGreenTemplate.textGreenScan(text);
        suggestion = resultMap.get("suggestion");
        if(!StrUtil.equals("pass",suggestion)){
            reason="文本内容中包含敏感信息";
        }

        //2、图片审核
        if(suggestion.equals("pass") && CollectionUtil.isNotEmpty(images)){
            resultMap = aliyunGreenTemplate.imageGreenScanForUrl(images);
            suggestion = resultMap.get("suggestion");
            if(!StrUtil.equals("pass",suggestion)){
                reason="图片中包含敏感信息";
            }
        }

        //3、将审核结果发送到MQ
        sendResultMessage(newsId,suggestion,reason);
    }

    private void sendResultMessage(Long newsId, String suggestion, String reason) {
        Map<String,Object> map = new HashMap<>();
        map.put("newsId",newsId);
        map.put("suggestion",suggestion);
        map.put("reason",reason);
        rabbitTemplate.convertAndSend(MessageConstants.GREEN_SCAN_RESULT_EXCHANGE, MessageConstants.NEWS_SCAN_KEY, JSONUtil.toJsonStr(map));
    }
}